<?php
/**
 * Created by PhpStorm.
 * User: jochen
 * Date: 2016/10/20
 * Time: 下午6:26
 */

namespace App\Services;

use App\Jobs\SendEmail;
use App\Mail\PassWord;
use App\Models\Company;
use Illuminate\Contracts\Logging\Log;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Support\Facades\DB;
use MongoException;

/**
 * Class PlatformService
 * @package App\Services
 *
 * 渠道后台相关逻辑
 */
class PlatformService
{
    use DispatchesJobs;
    /**
     * @param Company $company
     * @return string
     * @internal param $company_name
     */
    public function createGroupByCompany(Company $company) {
        try {
            $id = DB::table('groups')->insertGetId([
                'company_id' => $company->id,
                'name' => $company->name,
                'parent_id' => 0,
                'children' => [],
            ]);
            return strval($id);
        } catch (\MongoDuplicateKeyException $duplicateKeyException) {
            // todo write error log
        } catch (\Exception $mongoException) {
            // todo write error log
        }
        return null;
    }

    public function updateGroupByCompany(Company $company) {
        try {
            $group = DB::table('groups')
                ->where([
                    'company_id' => $company->id,
                    'parent_id' => 0,
                    'children' => ['$size' => 0],
                ])->update(['name' => $company->name]);
        } catch (\Exception $exception) {
            logger($exception->getMessage());
        }
    }

    /**
     * @param Company $company
     * @param array $userInfo
     * @return array|null  返回创建用户的id和明文密码
     */
    public function createUserAccount(Company $company, $userInfo) {
        if ($this->checkUserInfo($userInfo)) {
            try {
                // 密码明文
                $passwordCode = str_random(6);
                // 密码密文
                $password = bcrypt($passwordCode);
                // 发邮件
                $info = array_add($userInfo, 'password', $password);
                // 角色
                $role_id = $this->createSuperRole($userInfo['company_id']);
                $info['role_id'] = $role_id;
                $info['status'] = 1;
                if ($user_id = DB::table('users')->insertGetId($info)) {
                    // 记录密码明文
                    $this->logPassword($user_id, $userInfo, $passwordCode);
                    if (isset($userInfo['email']) && filter_var($userInfo['email'], FILTER_VALIDATE_EMAIL)) {
                        $userInfo['password'] = $passwordCode;
                        $userInfo['alias'] = $company->alias;
                        $userInfo['_id'] = (string) $user_id;
                        $job = (new SendEmail($userInfo));
                        dispatch($job);
                    }
                    return [strval($user_id), $passwordCode];
                }
            }
            catch (\MongoDuplicateKeyException $duplicateKeyException) {
                // 账号已存在
            }
            catch (\Exception $mongoException) {
                // todo write error to log
                logger($mongoException->getMessage());
            }
        }
        // 到这,说明创建失败,需要记录日志
        return null;
    }

    /**
     * @param null $company_id
     * @return array|null
     */
    public function createSuperRole($company_id = null) {
        $filter = [
            'company_id' => $company_id,
            'actions' => [],
        ];
        $role = DB::table('roles')->where($filter)->first();
        if (!$role) { // 没有找到? 创建一个新的
            $newRole = array_add($filter, 'title', '超级管理员');
            $role['_id'] = DB::table('roles')->insertGetId($newRole);
        }
        $role_id = strval($role['_id']);
        return $role_id;
    }

    public function isUserExist($mobile, $email = null)
    {
        if (empty($mobile)) return false;
        $query = DB::table('users')->where('mobile', $mobile);
        if (!is_null($email)) {
            $query = $query->orWhere('email', $email);
        }
        return $query->exists();
    }

    /**
     * @param $userInfo
     * @return bool
     */
    protected function checkUserInfo($userInfo) {
        if (isset($userInfo['name']) && isset($userInfo['company_id']) && isset($userInfo['mobile'])) {
            $r = $this->isUserExist($userInfo['mobile'], $userInfo['email']) ;
            return !$r;
        }
        return false;
    }

    protected function logPassword($userId, $userInfo, $password)
    {
        $passFile = storage_path('platform_users_pw.csv');

        $info = [
            'id' => $userId,
            'name' => $userInfo['name'],
            'password' => $password,
            'created_at' => strftime('%Y-%m-%d %H:%M:%S', time())
        ];
        if (!file_exists($passFile)) {
            file_put_contents($passFile, join(',', array_keys($info)).PHP_EOL);
        }
        file_put_contents($passFile, join(',', $info).PHP_EOL, FILE_APPEND);
    }
}